﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;

using CloudSoft.Workflows;

namespace ERPStore.Exporter.Workflows.Activities
{

	public sealed class CheckExportFileExists : CodeActivity
	{
		public InArgument<string> FileName { get; set; }
		public InArgument<bool> Force { get; set; }
		public OutArgument<bool> ExportExists { get; set; }

		protected override void Execute(CodeActivityContext context)
		{
			string fileName = context.GetValue(this.FileName);
			var force = context.GetValue(this.Force);
			var logger = context.GetService<ERPStore.Logging.ILogger>();

			context.ReportProgress(string.Format("Check exising file for {0}", fileName));
			logger.Info("Check existing file for {0}", fileName);
			if (force)
			{
				context.ReportProgress(string.Format("generation for {0} was forced", fileName));
				logger.Info("generation for {0} was forced", fileName);
				context.SetValue(ExportExists, false);
			}

			var nextStartDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 3, 0, 0);
			var fileInfo = new System.IO.FileInfo(fileName);
			if (fileInfo.Exists
				&& fileInfo.LastWriteTime.AddDays(1) > nextStartDate)
			{
				context.ReportProgress(string.Format("file {0} already generated since 24 hours", fileName));
				logger.Info("file {0} already generated since 24 hours", fileName);
				context.SetValue(ExportExists, true);
				return;
			}
			context.ReportProgress(string.Format("generation start for {0}", fileName));
			logger.Info("generation start for {0}", fileName);
			context.SetValue(ExportExists, false);
		}
	}
}
